import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QGridLayout, QHBoxLayout, QTextEdit
from PyQt5.QtGui import QColor, QPalette
from PyQt5.QtCore import Qt

class ColorContrastChecker(QWidget):
    def __init__(self):
        super().__init__()
        self.foreground_color = QColor(0, 0, 0)      # 黑色
        self.background_color = QColor(255, 255, 255) # 白色
        self.init_ui()
        
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 前景色选择
        fg_layout = QHBoxLayout()
        self.fg_display = QLabel('前景文本')
        self.fg_display.setFixedSize(100, 60)
        fg_btn = QPushButton('选择前景色')
        fg_btn.clicked.connect(self.select_foreground)
        
        fg_layout.addWidget(self.fg_display)
        fg_layout.addWidget(fg_btn)
        
        # 背景色选择  
        bg_layout = QHBoxLayout()
        self.bg_display = QLabel('背景')
        self.bg_display.setFixedSize(100, 60)
        bg_btn = QPushButton('选择背景色')
        bg_btn.clicked.connect(self.select_background)
        
        bg_layout.addWidget(self.bg_display)
        bg_layout.addWidget(bg_btn)
        
        # 预览区域
        self.preview_label = QLabel('文本可读性预览')
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setMinimumHeight(80)
        
        # 对比度信息
        self.contrast_info = QTextEdit()
        self.contrast_info.setReadOnly(True)
        self.contrast_info.setMaximumHeight(150)
        
        layout.addWidget(QLabel('前景色（文本颜色）:'))
        layout.addLayout(fg_layout)
        layout.addWidget(QLabel('背景色:'))
        layout.addLayout(bg_layout)
        layout.addWidget(QLabel('预览:'))
        layout.addWidget(self.preview_label)
        layout.addWidget(QLabel('对比度分析:'))
        layout.addWidget(self.contrast_info)
        
        self.update_display()
        self.setLayout(layout)
        self.setWindowTitle('颜色对比度检查器')
        
    def select_foreground(self):
        """选择前景色"""
        color = QColorDialog.getColor(
            self.foreground_color,
            self,
            "选择前景色（文本颜色）"
        )
        
        if color.isValid():
            self.foreground_color = color
            self.update_display()
            
    def select_background(self):
        """选择背景色"""
        color = QColorDialog.getColor(
            self.background_color,
            self,
            "选择背景色"
        )
        
        if color.isValid():
            self.background_color = color
            self.update_display()
            
    def calculate_contrast_ratio(self, color1, color2):
        """计算对比度比率（WCAG标准）"""
        def get_luminance(color):
            # 将sRGB颜色值转换为线性RGB
            r = color.red() / 255.0
            g = color.green() / 255.0
            b = color.blue() / 255.0
            
            # 应用sRGB转换公式
            r = r / 12.92 if r <= 0.03928 else ((r + 0.055) / 1.055) ** 2.4
            g = g / 12.92 if g <= 0.03928 else ((g + 0.055) / 1.055) ** 2.4
            b = b / 12.92 if b <= 0.03928 else ((b + 0.055) / 1.055) ** 2.4
            
            # 计算相对亮度
            return 0.2126 * r + 0.7152 * g + 0.0722 * b
            
        l1 = get_luminance(color1)
        l2 = get_luminance(color2)
        
        # 确保l1是较亮的颜色
        if l1 < l2:
            l1, l2 = l2, l1
            
        return (l1 + 0.05) / (l2 + 0.05)
        
    def update_display(self):
        """更新所有显示"""
        # 更新颜色显示
        self.fg_display.setStyleSheet(f"background-color: {self.foreground_color.name()}; border: 1px solid black;")
        self.bg_display.setStyleSheet(f"background-color: {self.background_color.name()}; border: 1px solid black;")
        
        # 更新预览
        self.preview_label.setStyleSheet(
            f"background-color: {self.background_color.name()}; "
            f"color: {self.foreground_color.name()}; "
            f"border: 2px solid black; font-size: 14px; font-weight: bold;"
        )
        
        # 计算并显示对比度信息
        contrast_ratio = self.calculate_contrast_ratio(self.foreground_color, self.background_color)
        
        # WCAG可访问性标准
        wcag_aa_normal = "通过" if contrast_ratio >= 4.5 else "失败"
        wcag_aa_large = "通过" if contrast_ratio >= 3.0 else "失败"
        wcag_aaa_normal = "通过" if contrast_ratio >= 7.0 else "失败"
        wcag_aaa_large = "通过" if contrast_ratio >= 4.5 else "失败"
        
        info = f"""对比度比率: {contrast_ratio:.2f}:1

WCAG 2.1 可访问性标准:
- AA级 (正常文本): {wcag_aa_normal} (要求 4.5:1)
- AA级 (大文本): {wcag_aa_large} (要求 3.0:1)  
- AAA级 (正常文本): {wcag_aaa_normal} (要求 7.0:1)
- AAA级 (大文本): {wcag_aaa_large} (要求 4.5:1)

颜色信息:
- 前景色: {self.foreground_color.name()}
- 背景色: {self.background_color.name()}
"""
        self.contrast_info.setPlainText(info)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ColorContrastChecker()
    window.show()
    sys.exit(app.exec_())
